// pages/wordDetail/wordDetail.js
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '../../../../../store/translationword/index'
Page({
  data: {
    entry: '',
    explain: [],
    listen: '',
    exam: '',
    mnemonic: {},
    pastExamSents: [],
    videoUrl: '',
    music: [],
    isplay: false,
    rel_word: [],
    Enword: [],
    // 存储音频上下文的引用
    innerAudioContext: null,
  },
  clickitem(e){
    // console.log(e.currentTarget.dataset.item);
    let item=e.currentTarget.dataset.item
    
    wx.navigateTo({
      url: `/packagesA/pages/translation/word/worddetail/index?item=${item}`,
    })
    const data=[...store.wordhistory]
    if(!data.includes(item))  data.push(item)
    this.updateword(data)
			
  },
  onLoad(options) {
    this.setData({
      entry: options.item,
      innerAudioContext: wx.createInnerAudioContext()
    })

    if (this.isChinese(this.data.entry)) {
      this.getdatachinese()
    } else {
      this.fetchData()
    }
     //在onload中创建
     this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['wordhistory'],
      actions: ['updateword']
    })
  },
  isChinese(str) {
    // 使用正则表达式匹配是否包含中文字符
    var pattern = /[\u4e00-\u9fa5]/;
    return pattern.test(str);
  },
  getdatachinese() {
    let that = this
    wx.request({
      url: 'http://dict.youdao.com/suggest?q=' + this.data.entry + '&num=1&doctype=json',
      success: (res) => {
        res.data.data.entries[0].explain.split(';').forEach(item => {
          wx.request({
            url: 'http://dict.youdao.com/suggest?q=' + item +
              '&num=1&doctype=json',
            method: "GET",
            success: (res) => {
              let data = [...that.data.Enword]
              data.push(res.data.data.entries[0])
              that.setData({
                Enword: data
              })

            }
          });
        })
      },

    });
  },
  fetchData(item) {
    let that = this
    wx.request({
      url: 'https://dict-mobile.iciba.com/interface/index.php?c=word&m=getsuggest&nums=10&is_need_mean=1&word=' + this.data.entry,
      success: (res) => {
        that.setData({
          entry: item,
          explain: res.data.message[0].means
        })

      },

    });
    wx.request({
      url: 'https://dict.youdao.com/jsonapi?q=' +
        this.data.entry,
      success(res) {
        console.log(res.data)
        if (res.data.collins) {
          that.setData({
            listen: '/' + res.data.collins.collins_entries[0].phonetic + '/'

          })
        }
        if (res.data.ec && res.data.ec.exam_type) {
          that.setData({
            exam: res.data.ec.exam_type.join('/')
          })
        }
        if (res.data.rel_word) {
          that.setData({
            rel_word: res.data.rel_word.rels
          })
        }
        if (res.data.individual) {
          that.setData({
            mnemonic: res.data.individual.mnemonic
          })
          for (let i = 0; i < 3; i++) {
            const data = [...that.data.pastExamSents]
            data.push(res.data.individual.pastExamSents[i]);
            that.setData({
              pastExamSents: data
            })
          }
        }



        if (res.data.word_video) {
          that.setData({
            videoUrl: res.data.word_video.word_videos[0].video.url
          })


        }

        if (res.data.music_sents) {
          that.setData({
            music: res.data.music_sents.sents_data
          })
        }
      },
    });
  },

  voiceplay(e) {
    if (this.data.isplay) return
    const item = e.currentTarget.dataset.item

    const innerAudioContext = this.data.innerAudioContext
    // innerAudioContext.autoplay = true;
    // http://dict.youdao.com/dictvoice?type=0&audio=' + key; key 是需要发音的单词，链接就是有道词典的接口链接，返回就是一个音频，直接可以播放，可以直接在游览器打开。
    wx.setInnerAudioOption({ obeyMuteSwitch: false });
    innerAudioContext.src = 'http://dict.youdao.com/dictvoice?type=0&audio=' + encodeURIComponent(item);
    wx.showLoading({
      title: '加载中'
    })
    this.setData({
      isplay: true
    })
    innerAudioContext.play()
    innerAudioContext.onPlay(() => {
      wx.hideLoading();
    });
    innerAudioContext.onEnded((res) => {
      wx.hideLoading();
      this.setData({
        isplay: false
      })
    });
    innerAudioContext.onError((res) => {
      wx.hideLoading();
      console.log(res.errMsg);
      console.log(res.errCode);
    });
  },
  voicemusic(e) {
    if (this.data.isplay) return
    const item = e.currentTarget.dataset.item;
    console.log(item);
    const innerAudioContext = this.data.innerAudioContext
    innerAudioContext.src = item;
    wx.setInnerAudioOption({ obeyMuteSwitch: false });
    wx.showLoading({
      title: '加载中'
    })
    this.setData({
      isplay: true
    })
    innerAudioContext.play()
    innerAudioContext.onPlay(() => {
      wx.hideLoading();
    });
    innerAudioContext.onEnded((res) => {
      wx.hideLoading();
      this.setData({
        isplay: false
      })
    });
    innerAudioContext.onError((res) => {
      wx.hideLoading();
      console.log(res.errMsg);
      console.log(res.errCode);
    });
  },
  // 停止音频播放的方法
  stopAudio() {
    if (this.data.innerAudioContext) {
      this.data.innerAudioContext.stop();
      this.data.innerAudioContext.destroy();
      this.setData({
        isplay: false
      });
    }
  },

  // 页面销毁时停止音频
  onUnload: function () {
    this.stopAudio();
  },

  // 页面隐藏时也可以停止音频，如果需要的话
  onHide: function () {
    this.stopAudio();
  }
});